<template>
    <view class="page">
        <!-- #ifdef MP-WEIXIN || MP-TOUTIAO -->
        <image :src="posterData" class="page" mode="scaleToFill" v-if="posterData" show-menu-by-longpress />
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <image :src="posterData" class="page" mode="scaleToFill" v-if="posterData" />
        <!-- #endif -->
        <canvas type="2d" class="page" canvas-id="poster" id="poster" :class="{ 'd-none': posterData }"></canvas>
    </view>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { onLoad, onReady, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { $system, $http, $page } from "@/utils";
import { useUserStore, useWebConfigStore, useRefs } from '@/stores';
const webConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(webConfigStore);
const userStore = useUserStore();
const { USERINFO } = useRefs(userStore);
let CanvasContext: any = null;
let canvas: any = null;
const dealer = ref({
    qrcode: ''
})
const posterData = ref('');
onReady(() => {
    // #ifdef H5
    CanvasContext = uni.createCanvasContext('poster');
    // #endif
    // #ifdef MP-WEIXIN
    const query = wx.createSelectorQuery()
    query.select('#poster')
        .fields({ node: true, size: true })
        .exec((res: any) => {
            canvas = res[0].node
            const ctx = canvas.getContext('2d')

            const dpr = wx.getSystemInfoSync().pixelRatio
            canvas.width = res[0].width * dpr
            canvas.height = res[0].height * dpr
            ctx.scale(dpr, dpr)
            CanvasContext = ctx;
            dealer.value.qrcode && draw();
        })
    // #endif
    // #ifdef MP-TOUTIAO
    const query = tt.createSelectorQuery()
    query.select('#poster')
        .node()
        .exec((res: any) => {
            canvas = res[0].node
            const ctx = canvas.getContext('2d')

            const dpr = tt.getSystemInfoSync().pixelRatio
            canvas.width = res[0].width * dpr
            canvas.height = res[0].height * dpr
            ctx.scale(dpr, dpr)
            CanvasContext = ctx;
            dealer.value.qrcode && draw();
        })
    // #endif
})
onLoad((options: any) => {
    getDealer();
})
onShareAppMessage(() => {
    return $page.shareMessage({
        path: `/pages/index/index`
    })
})
onShareTimeline(() => {
    return $page.shareTimeline({
        path: `/pages/index/index`
    })
})
const getDealer = () => {
    uni.showLoading({
        title: '加载中',
        mask: true
    })
    $http.get('Dealer/dealer').then((res: any) => {
        if (res.code === $http.ResponseCode.SUCCESS) {
            dealer.value = res.data;
            // #ifdef MP-WEIXIN
            dealer.value.qrcode = dealer.value.qrcode + '&platform=mp-weixin';
            // #endif
            // #ifdef MP-TOUTIAO
            dealer.value.qrcode = dealer.value.qrcode + '&platform=mp-toutiao';
            // #endif
            CanvasContext && draw();
        }
    })
}
const drawImage = async (url: string, x: number, y: number, w: number, h: number) => {
    // #ifdef H5
    CanvasContext.drawImage(url, x, y, w, h);
    step.value++;
    draw();
    // #endif
    // #ifdef MP-WEIXIN || MP-TOUTIAO
    const image = canvas.createImage();
    image.onload = () => {
        // 将图片绘制到 canvas 上
        CanvasContext.drawImage(image, x, y, w, h);
        step.value++;
        draw();
    }
    image.src = url;
    // #endif
}
const step = ref(0);
const draw = () => {
    const sInfo = $system.info();
    switch (step.value) {
        case 0:
            drawImage(`${$http.baseHOST}image/poster.jpg`, 0, 0, sInfo.windowWidth, sInfo.windowHeight);
            break;
        case 1:
            drawImage(dealer.value.qrcode, sInfo.windowWidth / 2 - 50, sInfo.windowHeight - 110, 100, 100);
            CanvasContext.save();
            break;
        case 2:
            // #ifdef H5
            CanvasContext.beginPath(); // 开始创建一个路径
            CanvasContext.arc(
                15 + sInfo.windowWidth / 2 - 15,
                15 + sInfo.windowHeight - 75,
                15,
                0,
                Math.PI * 2,
                false
            ); // 画一个圆形裁剪区域
            CanvasContext.clip();
            // 绘制头像图片
            drawImage(USERINFO.value.headimg, sInfo.windowWidth / 2 - 15, sInfo.windowHeight - 75, 30, 30);
            CanvasContext.restore();
            // 给头像加一个2px白边
            CanvasContext.strokeStyle = '#FFFFFF';
            CanvasContext.lineWidth = 2;
            CanvasContext.stroke();
            CanvasContext.save();
            CanvasContext.setFillStyle('#FFFFFF');
            CanvasContext.setFontSize(12);
            // 设置文字透明度
            CanvasContext.setGlobalAlpha(0.35);
            // #endif
            // #ifdef MP-WEIXIN || MP-TOUTIAO
            CanvasContext.fillStyle = '#FFFFFF';
            CanvasContext.font = '12px sans-serif';
            CanvasContext.globalAlpha = 0.35;
            // #endif
            // 在右下角添加WEBCONFIG.value.web_name
            CanvasContext.fillText(
                WEBCONFIG.value.web_name,
                sInfo.windowWidth - CanvasContext.measureText(WEBCONFIG.value.web_name).width - 10,
                sInfo.windowHeight - 10
            );
            CanvasContext.restore();
            step.value++;
            draw();
            break;
        case 3:
            // #ifdef H5
            CanvasContext.draw(false, () => {
                uni.hideLoading();
                saveImage();
            });
            // #endif
            // #ifdef MP-WEIXIN
            uni.hideLoading();
            setTimeout(() => {
                wx.canvasToTempFilePath({
                    canvasId: 'poster',
                    canvas: canvas,
                    success: (res: any) => {
                        console.log(res);
                        posterData.value = res.tempFilePath;
                    },
                    fail: (err: any) => {
                        console.log(err);
                        uni.showToast({
                            title: '生成图片失败',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            }, 100);
            // #endif
            // #ifdef MP-TOUTIAO
            uni.hideLoading();
            setTimeout(() => {
                tt.canvasToTempFilePath({
                    canvasId: 'poster',
                    canvas: canvas,
                    success: (res: any) => {
                        console.log(res);
                        posterData.value = res.tempFilePath;
                    },
                    fail: (err: any) => {
                        console.log(err);
                        uni.showToast({
                            title: '生成图片失败',
                            icon: 'none',
                            duration: 2000
                        })
                    }
                })
            }, 100);
            // #endif
            break;
    }
}
const saveImage = () => {
    uni.canvasToTempFilePath({
        canvasId: 'poster',
        success: (res) => {
            console.log(res);
            posterData.value = res.tempFilePath;
        },
        fail: (err) => {
            console.log(err);
            uni.showToast({
                title: '生成图片失败',
                icon: 'none',
                duration: 2000
            })
        }
    })
}
</script>
<style lang="scss" scoped>
.page {
    width: 100vw;
    height: calc(100vh - var(--window-top));
    display: block;
}

.d-none {
    display: none;
}
</style>